package com.megalith.exception;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.Map;

/**
*@Description 自定义异常处理
*
*  异常时用JSON代替HTML异常信息
*
*@Author lfp
*@Date 2021/4/12 15:16
*@Return
*/
@Slf4j
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {

    public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,
                                ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    /**
     * 获取异常属性
     */
    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        Throwable error = super.getError(request);
        int code; String errorMsg,errorDetail;
        if(error instanceof AuthException){
            code = 401;
            errorMsg = "无权访问";
            errorDetail = request.uri().toString();
        }else if(error instanceof ResponseStatusException){
            ResponseStatusException responseStatusException = (ResponseStatusException)error;
            code = responseStatusException.getStatus().value();
            errorMsg = responseStatusException.getStatus().getReasonPhrase();
            errorDetail = responseStatusException.getMessage();
        }else{
            code = 500;
            errorMsg = "服务端错误";
            errorDetail = buildMessage(request, error);
        }
        return response(code, errorMsg, errorDetail);
    }

    /**
     * 指定响应处理方法为JSON处理的方法
     * @param errorAttributes
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    /**
     * 根据code获取对应的HttpStatus
     * @param errorAttributes
     */
    @Override
    protected int getHttpStatus(Map<String, Object> errorAttributes) {
        int statusCode = (int) errorAttributes.get("code");
        return HttpStatus.valueOf(statusCode).value();
    }

    /**
     * 构建异常信息
     * @param request
     * @param ex
     * @return
     */
    protected String buildMessage(ServerRequest request, Throwable ex) {
        StringBuilder message = new StringBuilder("Failed to handle request [");
        message.append(request.methodName());
        message.append(" ");
        message.append(request.uri());
        message.append("]");
        if (ex != null) {
            message.append(": ");
            message.append(ex.getMessage());
        }
        return message.toString();
    }

    /**
     * 构建返回的JSON数据格式
     * @param status		状态码
     * @param errorMessage  异常信息
     * @return
     */
    protected Map<String, Object> response(int status, String errorMessage, String detail) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("code", status);
        map.put("message", errorMessage);
        map.put("detail", detail);
        return map;
    }

}